package com.zj.joke;

import java.util.List;

import android.R.integer;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import cn.sharesdk.framework.ShareSDK;
import cn.waps.AppConnect;

import com.activeandroid.ActiveAndroid;
import com.zj.joke.R;
import com.zj.joke.adapter.CategoryAdapter;
import com.zj.joke.db.DBCategory;
import com.zj.joke.db.DBItem;
import com.zj.joke.db.DBStoreItem;
import com.zj.joke.util.ActivityUtils;
import com.zj.joke.util.PreferenceUtils;
import com.zj.joke.view.CustomProgressDialog;
import com.zj.joke.view.QuitPopAd;

public class CategoryActivity extends ZJActivity implements
		OnItemClickListener, OnClickListener {
	private TextView mMoreTv;
	private TextView mSettingTv;
	private CustomProgressDialog mDialog;
	private CategoryAdapter mCategoryAdapter;
	private GridView mGridview;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		findViews();
		mDialog = CustomProgressDialog.createDialog(this);
		mDialog.setMessage("拼命加载中...");
		mDialog.setCancelable(true);
		initWanpuData();
	}

	private void initWanpuData() {
		// AppConnect.getInstance(this);
		AppConnect.getInstance("002d0e7becd6263d70644458d34167de", "appChina",
				this);
		// 迷你广告调用方式
		AppConnect.getInstance(this).setAdBackColor(
				Color.argb(100, 253, 238, 0));// 设置迷你广告背景颜色
		AppConnect.getInstance(this).setAdForeColor(Color.RED);// 设置迷你广告文字颜色
		LinearLayout miniLayout = (LinearLayout) findViewById(R.id.showMiniAd);
		// 预加载插屏广告内容（仅在使用到插屏广告的情况，才需要添加）//退出时用
		AppConnect.getInstance(this).initPopAd(this);
		// 预加载自定义广告内容（仅在使用了自定义广告、抽屉广告或迷你广告的情况，才需要添加）
		AppConnect.getInstance(this).initAdInfo();

		AppConnect.getInstance(this).setCrashReport(true);// 默认值true开启，设置false关闭
		String value = AppConnect.getInstance(this)
				.getConfig("say_hello", "no");
		if (!"no".equals(value)) {
			AppConnect.getInstance(this).showMiniAd(this, miniLayout, 10);// 10秒刷新一次
		}
	}

	private void findViews() {
		mMoreTv = (TextView) findViewById(R.id.mainMore);
		mMoreTv.setOnClickListener(this);
		mSettingTv = (TextView) findViewById(R.id.mainSetting);
		mSettingTv.setOnClickListener(this);
		mGridview = (GridView) findViewById(R.id.gridview);
		mCategoryAdapter = new CategoryAdapter(mContext);
		mGridview.setAdapter(mCategoryAdapter);
	}

	@Override
	protected void onResume() {
		super.onResume();
		new MyAsync().execute();
	}

	class MyAsync extends AsyncTask<String, Void, List<DBCategory>> {
		@Override
		protected void onPreExecute() {
			mDialog.show();
			super.onPreExecute();
		}

		@Override
		protected List<DBCategory> doInBackground(String... params) {
			List<DBCategory> dbCategories = DBCategory.getDBCategorys();

			if (dbCategories != null) {
				if (PreferenceUtils.isTimeToUpdate(mContext)) {
					ActiveAndroid.beginTransaction();
					try {
						for (int i = 0; i < dbCategories.size(); i++) {
							int count = (int) (Math.random() * 5);
							List<DBStoreItem> dbStoreItems = DBStoreItem
									.getDBStoreItems(
											dbCategories.get(i).category, count);

							for (int j = 0; j < dbStoreItems.size(); j++) {
								DBItem.add(dbStoreItems.get(j));
								dbStoreItems.get(j).delete();
							}
						}
						ActiveAndroid.setTransactionSuccessful();
					} finally {
						ActiveAndroid.endTransaction();
					}
				}
			}

			return dbCategories;
		}

		@Override
		protected void onPostExecute(List<DBCategory> result) {
			if (result != null) {
				mCategoryAdapter.setCategoryItems(result);
				mGridview.setOnItemClickListener(CategoryActivity.this);
			}
			if (mDialog != null && mDialog.isShowing()) {
				mDialog.dismiss();
			}
			super.onPostExecute(result);
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		DBCategory dbCategory = (DBCategory) parent.getItemAtPosition(position);
		Intent intent = new Intent();
		intent.setClass(this, ContentActivity.class);
		Bundle bundle = new Bundle();
		bundle.putString("category", dbCategory.category);
		intent.putExtras(bundle);
		startActivity(intent);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.mainMore:
			Intent intent = new Intent();
			intent.setClass(CategoryActivity.this, MoreActivity.class);
			startActivity(intent);
			overridePendingTransition(R.anim.push_left_in,
					R.anim.push_right_out);
			break;
		case R.id.mainSetting:
			Intent intent2 = new Intent();
			intent2.setClass(CategoryActivity.this, SettingActivity.class);
			startActivity(intent2);
			overridePendingTransition(R.anim.push_right_in,
					R.anim.push_left_out);
			break;
		}
	}

	@Override
	public void onBackPressed() {
		String value = AppConnect.getInstance(this)
				.getConfig("say_hello", "no");
		if ("no".equals(value)) {
			exitApp();
		} else {
			QuitPopAd.getInstance().show2(this);
		}
	}

	@Override
	protected void onDestroy() {
		ShareSDK.stopSDK(this);
		super.onDestroy();
	}

	private void exitApp() {
		Dialog alertDialog = new AlertDialog.Builder(this).setTitle("提示")
				.setMessage("确定要退出吗？")
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				})
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						AppConnect.getInstance(mContext).close();
						ShareSDK.stopSDK(mContext);
						ActivityUtils.getInstance().CloseAll();
					}
				}).create();
		alertDialog.show();
	}
}
